<template>
  <div class="home-container">
    <div class="upload-section">
      <h2>图片批量压缩</h2>
      <p class="description">上传您的图片，我们将为您提供高质量的压缩服务</p>
      
      <el-card class="upload-card">
        <div class="upload-area" @click="triggerFileInput" @dragover.prevent @drop.prevent="onDrop">
          <input
            type="file"
            ref="fileInput"
            multiple
            accept="image/png,image/jpeg,image/gif,image/webp"
            style="display: none"
            @change="handleFileChange"
          />
          
          <template v-if="!files.length">
            <el-icon class="upload-icon"><Upload /></el-icon>
            <div class="upload-text">
              <span>点击或拖拽图片到此区域上传</span>
              <p>支持PNG、JPG、GIF、WEBP格式</p>
            </div>
          </template>
          
          <div v-else class="file-list">
            <div v-for="(file, index) in files" :key="index" class="file-item">
              <div class="file-preview">
                <img :src="file.preview" alt="预览" />
              </div>
              <div class="file-info">
                <div class="file-name">{{ file.name }}</div>
                <div class="file-size">{{ formatFileSize(file.size) }}</div>
              </div>
              <el-button class="remove-btn" type="danger" circle @click.stop="removeFile(index)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>
        </div>
        
        <div class="upload-actions" v-if="files.length">
          <el-select v-model="compressionMethod" placeholder="选择压缩方式">
            <el-option label="TinyPNG API (高质量)" value="tinypng" />
            <el-option label="本地压缩 (快速)" value="local" />
          </el-select>
          
          <el-button type="primary" @click="uploadFiles" :loading="uploading">
            开始压缩 ({{ files.length }}张图片)
          </el-button>
          
          <el-button @click="clearFiles">清空</el-button>
        </div>
      </el-card>
    </div>
    
    <div class="results-section" v-if="results.length || (uploading && previousResults)">
      <h2>压缩结果</h2>
      
      <div v-if="uploading" class="loading-container">
        <el-skeleton :rows="5" animated />
        <div class="loading-text">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>正在压缩图片，请稍候...</span>
        </div>
      </div>
      
      <div v-else class="stats-summary">
        <div class="stat-item">
          <div class="stat-value">{{ results.length }}</div>
          <div class="stat-label">已处理图片</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ totalSavings }}%</div>
          <div class="stat-label">平均压缩率</div>
        </div>
        <div class="stat-item">
          <div class="stat-value">{{ formatFileSize(totalSavedSize) }}</div>
          <div class="stat-label">节省空间</div>
        </div>
      </div>
      
      <el-table v-if="!uploading" :data="results" style="width: 100%" border>
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <div class="result-preview">
              <img :src="scope.row.url" :alt="scope.row.filename" />
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="filename" label="文件名" />
        <el-table-column label="原始大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.original_size) }}
          </template>
        </el-table-column>
        <el-table-column label="压缩后大小" width="120">
          <template #default="scope">
            {{ formatFileSize(scope.row.compressed_size) }}
          </template>
        </el-table-column>
        <el-table-column label="压缩率" width="120">
          <template #default="scope">
            <el-progress
              :percentage="scope.row.compression_rate"
              :color="getColorByCompressionRate(scope.row.compression_rate)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template #default="scope">
            <el-button type="primary" size="small" @click="downloadImage(scope.row)">
              下载
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div v-if="!uploading" class="download-all">
        <el-button type="success" @click="downloadAllImages">
          下载全部图片
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { Delete, Upload, Loading } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

export default {
  name: 'HomePage',
  components: {
    Delete,
    Upload,
    Loading
  },
  setup() {
    const fileInput = ref(null)
    const files = ref([])
    const results = ref([])
    const uploading = ref(false)
    const compressionMethod = ref('tinypng')
    const previousResults = ref(false)
    
    const triggerFileInput = () => {
      fileInput.value.click()
    }
    
    const handleFileChange = (e) => {
      const selectedFiles = Array.from(e.target.files)
      addFiles(selectedFiles)
    }
    
    const onDrop = (e) => {
      const droppedFiles = Array.from(e.dataTransfer.files).filter(file => 
        file.type.startsWith('image/')
      )
      addFiles(droppedFiles)
    }
    
    const addFiles = (newFiles) => {
      for (const file of newFiles) {
        // 创建预览
        const reader = new FileReader()
        reader.onload = (e) => {
          files.value.push({
            file,
            name: file.name,
            size: file.size,
            preview: e.target.result
          })
        }
        reader.readAsDataURL(file)
      }
    }
    
    const removeFile = (index) => {
      files.value.splice(index, 1)
    }
    
    const clearFiles = () => {
      files.value = []
      fileInput.value.value = ''
    }
    
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }
    
    const uploadFiles = async () => {
      if (files.value.length === 0) {
        ElMessage.warning('请先选择要压缩的图片')
        return
      }
      
      uploading.value = true
      // 如果已有结果，标记为有之前的结果
      previousResults.value = results.value.length > 0
      
      try {
        const formData = new FormData()
        
        files.value.forEach(fileObj => {
          formData.append('files[]', fileObj.file)
        })
        
        formData.append('method', compressionMethod.value)
        
        const response = await axios.post('/api/compress', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        results.value = response.data.results
        
        if (results.value.length > 0) {
          ElMessage.success(`成功压缩 ${results.value.length} 张图片`)
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('图片压缩失败，请重试')
      } finally {
        uploading.value = false
        previousResults.value = false
      }
    }
    
    const downloadImage = (image) => {
      const link = document.createElement('a')
      link.href = image.url
      link.download = image.filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    }
    
    const downloadAllImages = () => {
      results.value.forEach(image => {
        downloadImage(image)
      })
    }
    
    const getColorByCompressionRate = (rate) => {
      if (rate < 20) return '#909399'
      if (rate < 40) return '#E6A23C'
      if (rate < 60) return '#67C23A'
      return '#409EFF'
    }
    
    const totalSavings = computed(() => {
      if (results.value.length === 0) return 0
      
      const totalSavingsPercentage = results.value.reduce((sum, result) => {
        return sum + (result.compression_rate || 0)
      }, 0) / results.value.length
      
      return Math.round(totalSavingsPercentage)
    })
    
    const totalSavedSize = computed(() => {
      return results.value.reduce((sum, result) => {
        return sum + (result.original_size - result.compressed_size)
      }, 0)
    })
    
    return {
      fileInput,
      files,
      results,
      uploading,
      compressionMethod,
      previousResults,
      triggerFileInput,
      handleFileChange,
      onDrop,
      removeFile,
      clearFiles,
      formatFileSize,
      uploadFiles,
      downloadImage,
      downloadAllImages,
      getColorByCompressionRate,
      totalSavings,
      totalSavedSize
    }
  }
}
</script>

<style scoped>
.home-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
}

.upload-section, .results-section {
  background-color: white;
  border-radius: 8px;
  padding: 2rem;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

h2 {
  margin-bottom: 0.5rem;
  color: #303133;
}

.description {
  color: #606266;
  margin-bottom: 1.5rem;
}

.upload-card {
  margin-top: 1rem;
}

.upload-area {
  border: 2px dashed #c0c4cc;
  border-radius: 6px;
  padding: 2rem;
  text-align: center;
  cursor: pointer;
  transition: border-color 0.3s;
}

.upload-area:hover {
  border-color: #409EFF;
}

.upload-icon {
  font-size: 4rem;
  color: #c0c4cc;
  margin-bottom: 1rem;
}

.upload-text {
  color: #606266;
}

.upload-text span {
  font-size: 1.1rem;
  display: block;
  margin-bottom: 0.5rem;
}

.upload-text p {
  font-size: 0.9rem;
  color: #909399;
}

.file-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 1rem;
}

.file-item {
  position: relative;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
}

.file-preview {
  height: 150px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
}

.file-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.file-info {
  padding: 0.5rem;
}

.file-name {
  font-size: 0.9rem;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size {
  font-size: 0.8rem;
  color: #909399;
}

.remove-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  opacity: 0.8;
}

.upload-actions {
  margin-top: 1.5rem;
  display: flex;
  gap: 1rem;
  justify-content: center;
}

.stats-summary {
  display: flex;
  justify-content: space-around;
  margin: 1.5rem 0;
  background-color: #f5f7fa;
  padding: 1.5rem;
  border-radius: 8px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 2rem;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 0.9rem;
  color: #606266;
}

.result-preview {
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  margin: 0 auto;
}

.result-preview img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.download-all {
  margin-top: 1.5rem;
  text-align: center;
}

.loading-container {
  padding: 2rem;
  text-align: center;
}

.loading-text {
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 1.5rem;
  color: #409EFF;
  font-size: 1.2rem;
}

.loading-icon {
  font-size: 1.5rem;
  margin-right: 0.5rem;
  animation: rotating 2s linear infinite;
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>